package com.remoter.cluster.internal.loadbalance;

import java.util.List;
import java.util.Random;

import com.remoter.basic.bean.support.ConsumerModule;
import com.remoter.basic.bean.support.ProviderModule;
import com.remoter.basic.cluster.support.AbstractLoadBalance;
import com.remoter.basic.util.ServiceLoader.MetaName;

/**
 * @author			koko
 * @date 			2017-08-09 11:53:09
 * @description 	类功能说明
 */
@MetaName("random")
public class RandomLoadBalance extends AbstractLoadBalance{
	
	private final Random random = new Random(); 
	
	@Override
	protected ProviderModule doSelect(ConsumerModule consumer,List<ProviderModule> providers) {
		int length = providers.size();
		int totalWeight = 0;
		boolean sameWeight = true;
		for(int i=0;i<length;i++){
			int weight = this.getWeight(providers.get(i));
			totalWeight += weight;
			if(sameWeight && i>0 && weight != this.getWeight(providers.get(i-1))){
				sameWeight = false;
			}
		}
		if(totalWeight > 0 && !sameWeight){
			int offset = random.nextInt(totalWeight);
			for(int i=0;i<length;i++){
				offset -= this.getWeight(providers.get(i));
				if(offset < 0){
					return providers.get(i);
				}
			}
		}
		return providers.get(random.nextInt(length));
	}
	
}